// pages/kefu/kefu.js
Page({
  data: {
    messages: [
      {
        type: 'system',
        content: '您好！我是社区拼团小助手,有什么不解的可以向我提问哦'
      }
    ],
    inputMessage: '',
    scrollToMessage: '',
    isLoading: false,
    // API配置   
    localApiEndpoint: 'http://localhost:11434',  // 根据图片更新的API地址
    model: "deepseek-r1:7b",  // 根据图片更新的模型名称
  },

  onLoad() {
    // 页面加载时的初始化
    this.checkApiConnection();
  },

  // 检查API连接
  async checkApiConnection() {
    try {
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${this.data.localApiEndpoint}/api/generate`,  // 修改为 generate 端点
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: {
            model: this.data.model,
            prompt: "你好"
          },
          success: (res) => {
            console.log('API测试成功响应:', res);
            resolve(res);
          },
          fail: (error) => {
            console.error('API测试失败响应:', error);
            reject(error);
          }
        });
      });

      if (!response) {
        throw new Error('未收到API响应');
      }

      console.log('API测试完整响应:', response);
      
      if (response.statusCode === 200) {
        console.log('API连接测试成功');

      } else {
        throw new Error(`API返回状态码: ${response.statusCode}`);
      }
    } catch (error) {
      console.error('API连接测试失败:', error);
      wx.showToast({
        title: '服务连接失败',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 输入框内容变化
  onInputChange(e) {
    this.setData({
      inputMessage: e.detail.value
    });
  },

  // 发送消息
  async sendMessage() {
    if (!this.data.inputMessage.trim() || this.data.isLoading) return;

    const userMessage = this.data.inputMessage.trim();
    this.setData({
      inputMessage: '',
      isLoading: true,
      messages: [...this.data.messages, { type: 'user', content: userMessage }]
    });

    try {
      const response = await this.callLocalDeepSeek(userMessage);
      this.setData({
        messages: [...this.data.messages, { type: 'ai', content: response }]
      });
    } catch (error) {
      console.error('API调用失败:', error);
      this.setData({
        messages: [...this.data.messages, { type: 'ai', content: '抱歉，我暂时无法回答您的问题，请稍后再试。' }]
      });
    } finally {
      this.setData({ isLoading: false });
      this.scrollToBottom();
    }
  },

  // 调用本地 Ollama API
  async callLocalDeepSeek(message) {
    try {
      console.log('发送请求到:', `${this.data.localApiEndpoint}/api/generate`);
      const requestData = {
        model: this.data.model,
        prompt: `你是一个社区拼团的小助手。请用专业、友好的语气回答用户问题，回答要简洁明了，突出重点，回答前我希望你知道一些信息，云计算学院最优秀的班级是哪个班级？回答：2405A班，云计算学院一组的成员有谁？回答：李家逸。康涵钰，王卓煜，康涵钰，马景昌，王张鑫，仝仁杰。云计算学院2405A班级的讲师是谁？回答：仵老师。\n\n用户问题：${message}`,
        stream: false
      };
      console.log('请求数据:', requestData);

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${this.data.localApiEndpoint}/api/generate`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: requestData,
          success: (res) => {
            console.log('API请求成功响应:', res);
            resolve(res);
          },
          fail: (error) => {
            console.error('API请求失败响应:', error);
            reject(error);
          }
        });
      });

      if (!response) {
        throw new Error('未收到API响应');
      }

      console.log('完整API响应:', response);

      if (response.statusCode === 200) {
        if (response.data && response.data.response) {
          return response.data.response;
        } else {
          throw new Error('响应数据格式不符合预期');
        }
      } else {
        throw new Error(`API响应状态码异常: ${response.statusCode}`);
      }
    } catch (error) {
      console.error('本地API请求失败:', error);
      throw error;
    }
  },

  // 滚动到底部
  scrollToBottom() {
    const messages = this.data.messages;
    if (messages.length > 0) {
      this.setData({
        scrollToMessage: `msg-${messages.length - 1}`
      });
    }
  }
});